package class03;

public class Code10_IsBalanced {

    public static class Node {
        public int value;
        public Node left;
        public Node right;

        public Node(int data) {
            this.value = data;
        }
    }


    static class Info {
        int height;
        boolean balance;

        Info(int h, boolean b) {
            this.height = h;
            this.balance = b;
        }

    }

    static boolean isBalanced1(Node head) {
        return process(head).balance;
    }

    static Info process(Node head) {
        if (null == head) {
            return new Info(0, true);
        }
        Info left = process(head.left);
        Info right = process(head.right);


        boolean flag = true;

        if (!left.balance) {
            flag = false;
        }


        if (!right.balance) {
            flag = false;
        }

        if (Math.abs(left.height - right.height) + 1 > 1) {
            flag = false;
        }
        return new Info(Math.max(left.height, right.height) + 1, flag);


    }


    public static void main(String[] args) {

            Node head = new Node(1);
            head.left = new Node(2);
            head.right = new Node(3);
            head.left.left = new Node(4);
            head.left.right = new Node(5);
            head.right.left = new Node(6);
            head.right.right = new Node(7);
            System.out.println(isBalanced1(head));


    }
}